layui.use(['carousel', 'form', 'jquery', 'element'], function() {
  var carousel = layui.carousel
    , form = layui.form
    , element = layui.element
    , $ = layui.$;

  // 定义一个通过地址栏参数名称获取对应值的函数
  function GetQueryString(name) {
      let reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
      let r = window.location.search.substr(1).match(reg);
      if (r!=null){
          return decodeURI(r[2]);
      }else{
          return null;
      }
  }
  let search = GetQueryString('search');
  let id = GetQueryString('id');
  // if (!search){
  //   location.href = '/static/index.html'
  // }
  // 在search.html页面搜索框中显示关键词
  $('#inputKeywords').val(search);

  // 定义一个展示函数
  function commodity_show(data) {
    let commodity_list = data.data;
    let content = ``;
    console.log(commodity_list);
    $.each(commodity_list,function (i,commodity) {
      let title = commodity._source.title
      if (commodity.highlight){
        title = commodity.highlight.title[0]
      }
      let subtitle = commodity._source.subtitle;
      let pic = commodity._source.pic;
      content += `<div class="layui-col-sm3">
                    <div class="grid-demo grid-demo-bg1">
                        <div class="layui-card"><a href="/static/detail.html?id=${commodity._id}">
                            <div class="layui-card-header">
                                <img src="${pic}" alt="">
                            </div>
                            <div class="layui-card-body">
                                <a href="">${title}</a>
                                <p>
                                    ${subtitle}
                                </p>
                            </div>
                        </a></div>
                    </div>
                  </div>`
    });
    $('.search_commodity').html(content);
  }
  // 搜索商品展示
  function commodity_search(){
    $('.search_commodity').html(''); // 清空展示页
    $.get('/commodity/search/',{"search":search},function (data) {
      commodity_show(data);
    });
  }

  // 点击菜单商品结果展示
  function commodity_menu(){
    $('.search_commodity').html(''); // 清空展示页
    $.get('/commodity/by_menu/',{"id":id},function (data) {
      commodity_show(data);
    });
  }

  // 分情况实现商品展示
  if(search != null){
      commodity_search();
  }else if(id != null){
      commodity_menu();
  }else{
      location.href = '/static/index.html'
  }

})